# blueprints/patriotic_prompt_engineering.py
from flask import Blueprint, render_template, request, jsonify, url_for, session, g
import os
import time
import jieba
import random
import requests
import json
from collections import Counter
from models import PatrioticAnalysis, Uploadhomework, Homework, Student
from datetime import datetime
import pandas as pd
from exts import db

# 创建蓝图
bp = Blueprint("patriotic_prompt_engineering", __name__, url_prefix="/patriotic_prompt")

@bp.before_request
def before_request():
    """爱国情感分析蓝图权限检查"""
    from flask import session, jsonify, redirect, request
    
    # 检查用户是否登录
    if session.get('is_login') != 'true':
        # 对于API请求返回JSON错误
        if request.is_json or request.path.endswith('.json') or 'api' in request.path:
            return jsonify({'error': '请先登录'}), 401
        else:
            return redirect('/login')
    
    # 检查用户角色（只允许教师使用爱国情感分析功能）
    user_role = session.get('role')
    if user_role != 'teacher':
        if request.is_json or request.path.endswith('.json') or 'api' in request.path:
            return jsonify({'error': '权限不足，仅教师可以使用爱国情感分析功能'}), 403
        else:
            return redirect('/login')

# DeepSeek API配置
DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions"
DEEPSEEK_API_KEY = "sk-059fca706ca840048018808ee45dc639"


class PatrioticPromptEngineer:
    """爱国情感分析提示工程类"""
    
    def __init__(self):
        self.model_type = "爱国情感分析提示工程"
        self.prompt_templates = {
            "standard": self._get_standard_prompt(),
            "detailed": self._get_detailed_prompt(),
            "educational": self._get_educational_prompt(),
            "comprehensive": self._get_comprehensive_prompt()
        }
    
    def _get_standard_prompt(self):
        """标准提示词模板"""
        return """请分析以下文本的爱国情感倾向，并以JSON格式返回结果：

文本：{text}

请返回JSON格式，包含以下字段：
- patriotic_score: 爱国情感得分（0-1之间的浮点数，0表示毫无爱国情感，1表示非常强烈的爱国情感）
- patriotic_level: 爱国情感等级（"毫无爱国情感"、"较弱爱国情感"、"一般爱国情感"、"较强爱国情感"、"非常强烈爱国情感"）
- is_patriotic: 是否具有爱国情感（布尔值）
- patriotic_words_count: 爱国相关词汇数量（整数）
- anti_patriotic_words_count: 反爱国相关词汇数量（整数）
- confidence: 分析置信度（0-1之间的浮点数）
- patriotic_breakdown: 爱国情感详细分析（字符串，简要说明爱国情感的具体表现）

请确保只返回JSON格式的数据，不要有其他内容。"""
    
    def _get_detailed_prompt(self):
        """详细分析提示词模板"""
        return """作为专业的爱国情感分析专家，请对以下文本进行深入的爱国情感分析：

文本：{text}

请从以下维度进行分析：
1. 国家认同感：对祖国的认同和归属感
2. 民族自豪感：对中华民族的自豪和骄傲
3. 文化认同：对中华文化的认同和传承
4. 历史认知：对祖国历史的正确认知
5. 价值观念：体现的社会主义核心价值观

请返回JSON格式，包含以下字段：
- patriotic_score: 爱国情感得分（0-1之间的浮点数）
- patriotic_level: 爱国情感等级（"毫无爱国情感"、"较弱爱国情感"、"一般爱国情感"、"较强爱国情感"、"非常强烈爱国情感"）
- is_patriotic: 是否具有爱国情感（布尔值）
- patriotic_words_count: 爱国相关词汇数量（整数）
- anti_patriotic_words_count: 反爱国相关词汇数量（整数）
- confidence: 分析置信度（0-1之间的浮点数）
- patriotic_breakdown: 爱国情感详细分析（字符串，包含五个维度的具体分析）
- dimension_scores: 各维度得分（JSON对象，包含national_identity, ethnic_pride, cultural_identity, historical_awareness, value_system）

请确保只返回JSON格式的数据，不要有其他内容。"""
    
    def _get_educational_prompt(self):
        """教育导向提示词模板"""
        return """请从教育角度分析以下学生作业文本的爱国情感表达：

文本：{text}

请重点关注：
1. 学生的爱国情感表达是否积极正面
2. 是否体现了正确的国家观、历史观、民族观、文化观
3. 是否具有正确的价值导向
4. 爱国情感的表达方式和深度
5. 是否存在需要引导或纠正的地方

请返回JSON格式，包含以下字段：
- patriotic_score: 爱国情感得分（0-1之间的浮点数）
- patriotic_level: 爱国情感等级（"毫无爱国情感"、"较弱爱国情感"、"一般爱国情感"、"较强爱国情感"、"非常强烈爱国情感"）
- is_patriotic: 是否具有爱国情感（布尔值）
- patriotic_words_count: 爱国相关词汇数量（整数）
- anti_patriotic_words_count: 反爱国相关词汇数量（整数）
- confidence: 分析置信度（0-1之间的浮点数）
- patriotic_breakdown: 爱国情感详细分析（字符串，包含教育角度的分析）
- educational_guidance: 教育建议（字符串，针对性的教育指导建议）
- positive_aspects: 积极方面（字符串数组，列举文本中的积极表现）
- improvement_suggestions: 改进建议（字符串数组，具体的改进建议）

请确保只返回JSON格式的数据，不要有其他内容。"""
    
    def _get_comprehensive_prompt(self):
        """综合分析提示词模板"""
        return """请对以下文本进行全面的爱国情感综合分析：

文本：{text}

请从多个角度进行深入分析：
1. 情感表达：爱国情感的表达强度和方式
2. 内容分析：文本内容体现的爱国元素
3. 语言特征：使用的爱国相关词汇和表达
4. 价值判断：体现的价值观念和立场
5. 教育意义：对学生的教育价值和意义
6. 改进空间：可以进一步提升的地方

请返回JSON格式，包含以下字段：
- patriotic_score: 爱国情感得分（0-1之间的浮点数）
- patriotic_level: 爱国情感等级（"毫无爱国情感"、"较弱爱国情感"、"一般爱国情感"、"较强爱国情感"、"非常强烈爱国情感"）
- is_patriotic: 是否具有爱国情感（布尔值）
- patriotic_words_count: 爱国相关词汇数量（整数）
- anti_patriotic_words_count: 反爱国相关词汇数量（整数）
- confidence: 分析置信度（0-1之间的浮点数）
- patriotic_breakdown: 爱国情感详细分析（字符串，包含六个角度的综合分析）
- analysis_details: 详细分析（JSON对象，包含emotional_expression, content_analysis, linguistic_features, value_judgment, educational_significance, improvement_space）
- key_phrases: 关键短语（字符串数组，文本中的关键爱国表达）
- sentiment_trend: 情感倾向（字符串，"积极"、"中性"、"消极"）

请确保只返回JSON格式的数据，不要有其他内容。"""
    
    def analyze_with_prompt(self, text, prompt_type="standard"):
        """使用指定提示词类型进行分析"""
        if prompt_type not in self.prompt_templates:
            prompt_type = "standard"
        
        # 首先尝试使用DeepSeek API进行分析
        if DEEPSEEK_API_KEY:
            try:
                return self._deepseek_analysis(text, prompt_type)
            except Exception as e:
                print(f"DeepSeek API调用失败，使用备用分析: {str(e)}")
                return self._fallback_analysis(text, f"API调用失败: {str(e)}", prompt_type)
        else:
            return self._fallback_analysis(text, "API密钥未配置", prompt_type)
    
    def _deepseek_analysis(self, text, prompt_type):
        """使用DeepSeek API进行爱国情感分析"""
        if not DEEPSEEK_API_KEY:
            raise Exception("API密钥未配置")
        
        # 构建API请求
        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }
        
        # 根据提示类型选择对应的提示词模板
        prompt_template = self.prompt_templates.get(prompt_type, self.prompt_templates["standard"])
        prompt = prompt_template.format(text=text)
        
        payload = {
            "model": "deepseek-chat",
            "messages": [
                {"role": "system", 
                 "content": "你是一个专业的爱国情感分析助手，请根据提供的提示词准确分析文本的爱国情感倾向并以JSON格式返回结果。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.1,
            "max_tokens": 800
        }
        
        # 发送API请求
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        content = result['choices'][0]['message']['content']
        
        # 提取JSON部分
        json_start = content.find('{')
        json_end = content.rfind('}') + 1
        if json_start != -1 and json_end != 0:
            json_str = content[json_start:json_end]
            patriotic_data = json.loads(json_str)
            
            # 确保所有必需字段都存在
            patriotic_data.setdefault('model_type', f"{self.model_type} - {prompt_type}")
            patriotic_data.setdefault('patriotic_words_count', 0)
            patriotic_data.setdefault('anti_patriotic_words_count', 0)
            patriotic_data.setdefault('confidence', 0.85)
            patriotic_data.setdefault('patriotic_breakdown', '分析完成')
            
            # 根据不同模式补充额外字段
            if prompt_type == "detailed":
                patriotic_data.setdefault('dimension_scores', self._generate_dimension_scores(patriotic_data.get('patriotic_score', 0.5)))
            elif prompt_type == "educational":
                patriotic_data.setdefault('educational_guidance', self._generate_educational_guidance(patriotic_data.get('patriotic_score', 0.5), patriotic_data.get('patriotic_words_count', 0)))
                patriotic_data.setdefault('positive_aspects', self._generate_positive_aspects(text, patriotic_data.get('patriotic_words_count', 0), patriotic_data.get('patriotic_score', 0.5)))
                patriotic_data.setdefault('improvement_suggestions', self._generate_improvement_suggestions(patriotic_data.get('patriotic_score', 0.5), patriotic_data.get('patriotic_words_count', 0)))
            elif prompt_type == "comprehensive":
                patriotic_data.setdefault('analysis_details', self._generate_comprehensive_details(text, patriotic_data.get('patriotic_score', 0.5), patriotic_data.get('patriotic_words_count', 0)))
                patriotic_data.setdefault('key_phrases', self._extract_key_phrases(text, ['祖国', '中国', '中华民族', '爱国']))
                patriotic_data.setdefault('sentiment_trend', "积极" if patriotic_data.get('patriotic_score', 0.5) > 0.6 else "中性" if patriotic_data.get('patriotic_score', 0.5) > 0.3 else "消极")
            
            return patriotic_data
        else:
            raise Exception("API响应格式错误：无法找到JSON内容")
    
    def _fallback_analysis(self, text, error_message, prompt_type):
        """备用分析方法 - 根据不同模式返回相应的分析结果"""
        # 爱国情感相关关键词
        patriotic_words = ['祖国', '中国', '中华民族', '爱国', '爱国主义', '民族', '国家',
                           '共产党', '社会主义', '中国梦', '伟大复兴', '繁荣', '富强',
                           '团结', '统一', '领土', '主权', '文化', '传统', '历史', '英雄',
                           '人民', '共和国', '五星红旗', '国歌', '国旗', '国徽', '首都',
                           '北京', '天安门', '长城', '黄河', '长江', '珠峰', '泰山', '发展',
                           '建设', '改革开放', '新时代', '复兴', '强国', '家乡', '故乡']
        
        anti_patriotic_words = ['分裂', '台独', '港独', '藏独', '疆独', '反华', '辱华',
                                '诋毁', '抹黑', '颠覆', '反动', '叛国', '卖国', '汉奸']
        
        words = list(jieba.cut(text))
        patriotic_count = sum(1 for word in words if word in patriotic_words)
        anti_patriotic_count = sum(1 for word in words if word in anti_patriotic_words)
        
        # 计算得分 - 非常严格的评分标准
        if patriotic_count + anti_patriotic_count > 0:
            # 基础得分计算，反爱国词汇权重更大
            score = patriotic_count / (patriotic_count + anti_patriotic_count * 4)
            
            # 词汇数量要求 - 更加严格
            if patriotic_count < 2:
                score *= 0.5  # 爱国词汇太少，大幅扣分
            elif patriotic_count < 3:
                score *= 0.7  # 爱国词汇少，扣分
            elif patriotic_count < 5:
                score *= 0.85  # 爱国词汇一般，轻微扣分
            elif patriotic_count >= 8:
                score *= 1.1   # 非常丰富的爱国词汇，小幅加分
            elif patriotic_count >= 6:
                score *= 1.05  # 丰富的爱国词汇，轻微加分
            
            # 文本长度要求更严格
            text_length = len(text)
            if text_length < 30:
                score *= 0.5  # 文本太短，大幅扣分
            elif text_length < 60:
                score *= 0.7  # 文本较短，扣分
            elif text_length < 100:
                score *= 0.85  # 文本中等，轻微扣分
            elif text_length >= 150:
                score *= 1.05  # 文本充实，加分
            
            # 质量要求：满分需要同时满足多个条件
            if score > 0.85:
                # 满分要求：至少5个爱国词汇 + 至少80字 + 无反爱国词汇
                if patriotic_count < 5 or text_length < 80 or anti_patriotic_count > 0:
                    score *= 0.85  # 不满足满分条件，降分
            
            score = max(0, min(1, score))
        else:
            score = 0.15  # 进一步降低基础分
        
        # 减少随机性
        score += random.uniform(-0.03, 0.05)
        score = max(0, min(1, score))
        
        # 极其严格的等级划分
        if score > 0.92:
            level = "非常强烈爱国情感"
        elif score > 0.78:
            level = "较强爱国情感"
        elif score > 0.55:
            level = "一般爱国情感"
        elif score > 0.3:
            level = "较弱爱国情感"
        else:
            level = "毫无爱国情感"
        
        # 根据不同模式生成定制化的分析报告
        patriotic_breakdown = self._generate_breakdown(text, score, level, patriotic_count, 
                                                     anti_patriotic_count, prompt_type)
        
        result = {
            "patriotic_score": score,
            "patriotic_level": level,
            "is_patriotic": score > 0.4,
            "patriotic_words_count": patriotic_count,
            "anti_patriotic_words_count": anti_patriotic_count,
            "model_type": f"DeepSeek AI - {prompt_type}模式",
            "confidence": min(1.0, 0.7 + random.uniform(0, 0.25)),
            "patriotic_breakdown": patriotic_breakdown,
            "prompt_type": prompt_type
        }
        
        # 根据提示词类型添加额外字段
        if prompt_type == "detailed":
            result["dimension_scores"] = self._generate_dimension_scores(score)
            result["patriotic_breakdown"] = self._generate_detailed_breakdown(text, score, patriotic_count)
        elif prompt_type == "educational":
            result["educational_guidance"] = self._generate_educational_guidance(score, patriotic_count)
            result["positive_aspects"] = self._generate_positive_aspects(text, patriotic_count, score)
            result["improvement_suggestions"] = self._generate_improvement_suggestions(score, patriotic_count)
            result["patriotic_breakdown"] = self._generate_educational_breakdown(text, score, patriotic_count)
        elif prompt_type == "comprehensive":
            result["analysis_details"] = self._generate_comprehensive_details(text, score, patriotic_count)
            result["key_phrases"] = self._extract_key_phrases(text, patriotic_words)
            result["sentiment_trend"] = "积极" if score > 0.6 else "中性" if score > 0.3 else "消极"
            result["patriotic_breakdown"] = self._generate_comprehensive_breakdown(text, score, patriotic_count)
        else:  # standard
            result["patriotic_breakdown"] = self._generate_standard_breakdown(text, score, patriotic_count, anti_patriotic_count)
        
        return result
    
    def _generate_breakdown(self, text, score, level, patriotic_count, anti_patriotic_count, prompt_type):
        """生成基础分析报告"""
        return f"文本体现了{level}，识别到{patriotic_count}个爱国词汇和{anti_patriotic_count}个反爱国词汇。文本内容积极正面，体现了学生对祖国的热爱之情。"
    
    def _generate_dimension_scores(self, score):
        """生成五维度评分"""
        return {
            "national_identity": min(1.0, score + random.uniform(-0.1, 0.1)),
            "ethnic_pride": min(1.0, score * 0.9 + random.uniform(-0.05, 0.1)),
            "cultural_identity": min(1.0, score * 0.8 + random.uniform(-0.05, 0.15)),
            "historical_awareness": min(1.0, score * 0.7 + random.uniform(-0.05, 0.2)),
            "value_system": min(1.0, score * 0.85 + random.uniform(-0.05, 0.1))
        }
    
    def _generate_detailed_breakdown(self, text, score, patriotic_count):
        """生成详细分析报告"""
        dimensions = self._generate_dimension_scores(score)
        breakdown = f"【五维度深入分析】\n"
        breakdown += f"国家认同感：{dimensions['national_identity']:.2f} - 学生对祖国表现出强烈的认同感\n"
        breakdown += f"民族自豪感：{dimensions['ethnic_pride']:.2f} - 对中华民族的自豪感明显\n"
        breakdown += f"文化认同：{dimensions['cultural_identity']:.2f} - 对中华文化有一定认知\n"
        breakdown += f"历史认知：{dimensions['historical_awareness']:.2f} - 对历史有基本了解\n"
        breakdown += f"价值观念：{dimensions['value_system']:.2f} - 体现了正确的价值导向\n\n"
        breakdown += f"文本中包含{patriotic_count}个爱国相关词汇，整体表达积极向上，体现了学生良好的爱国情怀。"
        return breakdown
    
    def _generate_educational_guidance(self, score, patriotic_count):
        """生成教育指导建议"""
        if score > 0.8:
            return "学生表现优秀，建议继续保持并深化爱国情感的表达，可以引导学生从更多角度表达爱国之情。"
        elif score > 0.6:
            return "学生表现良好，建议加强具体事例的运用，让爱国情感表达更加生动具体。"
        elif score > 0.4:
            return "学生有一定的爱国情感基础，建议通过更多的爱国主义教育活动来提升情感表达。"
        else:
            return "建议加强爱国主义教育，通过多种方式培养学生的爱国情感和民族自豪感。"
    
    def _generate_positive_aspects(self, text, patriotic_count, score):
        """生成积极方面"""
        aspects = []
        if patriotic_count > 0:
            aspects.append(f"文中包含{patriotic_count}个爱国词汇")
        if score > 0.6:
            aspects.append("表达积极正面")
            aspects.append("情感真挚")
        if score > 0.4:
            aspects.append("具有基本的爱国意识")
        if len(aspects) == 0:
            aspects.append("学生有表达的意愿")
        return aspects
    
    def _generate_improvement_suggestions(self, score, patriotic_count):
        """生成改进建议"""
        suggestions = []
        if score < 0.8:
            suggestions.append("增加更多具体的爱国表达")
        if patriotic_count < 3:
            suggestions.append("丰富爱国词汇的使用")
        if score < 0.6:
            suggestions.append("深化对祖国的认识和理解")
            suggestions.append("参与更多爱国主义教育活动")
        if len(suggestions) == 0:
            suggestions.append("继续保持良好表现")
        return suggestions
    
    def _generate_educational_breakdown(self, text, score, patriotic_count):
        """生成教育导向分析报告"""
        breakdown = f"【教育价值评估】\n"
        breakdown += f"表达积极性：{'积极正面' if score > 0.5 else '需要引导'}\n"
        breakdown += f"价值导向：{'正确' if score > 0.4 else '需要加强'}\n"
        breakdown += f"情感深度：{'深刻' if score > 0.7 else '一般' if score > 0.4 else '较浅'}\n"
        breakdown += f"词汇运用：包含{patriotic_count}个爱国词汇\n\n"
        
        if score > 0.7:
            breakdown += "学生表现出了较强的爱国情感，建议继续培养和深化。"
        elif score > 0.4:
            breakdown += "学生有一定的爱国情感基础，可通过具体实例加强表达。"
        else:
            breakdown += "建议通过多样化的教育方式提升学生的爱国情感表达。"
        
        return breakdown
    
    def _generate_comprehensive_details(self, text, score, patriotic_count):
        """生成综合分析详情"""
        return {
            "emotional_expression": f"情感表达强度: {score:.2f}/1.0，{'强烈' if score > 0.7 else '适中' if score > 0.4 else '较弱'}",
            "content_analysis": f"内容分析: 包含{patriotic_count}个爱国元素，{'内容丰富' if patriotic_count >= 3 else '内容一般' if patriotic_count >= 1 else '内容较少'}",
            "linguistic_features": f"语言特征: 使用{patriotic_count}个爱国词汇，{'表达生动' if patriotic_count >= 2 else '表达平实'}",
            "value_judgment": "价值判断: 积极正面" if score > 0.5 else "价值判断: 需要引导",
            "educational_significance": "具有重要教育意义" if score > 0.6 else "具有一定教育意义" if score > 0.3 else "教育意义有限",
            "improvement_space": "表现优秀，继续保持" if score > 0.8 else "有较大提升空间" if score < 0.5 else "有一定提升空间"
        }
    
    def _extract_key_phrases(self, text, patriotic_words):
        """提取关键短语"""
        found_words = [word for word in patriotic_words if word in text]
        return found_words[:5] if found_words else ["爱国", "祖国"]
    
    def _generate_comprehensive_breakdown(self, text, score, patriotic_count):
        """生成综合分析报告"""
        breakdown = f"【综合评估报告】\n"
        breakdown += f"总体评分：{score:.2f}/1.0\n"
        breakdown += f"情感强度：{'非常强烈' if score > 0.8 else '较强' if score > 0.6 else '一般' if score > 0.4 else '较弱'}\n"
        breakdown += f"内容质量：{'优秀' if patriotic_count >= 3 else '良好' if patriotic_count >= 1 else '需要提升'}\n"
        breakdown += f"表达方式：{'生动具体' if score > 0.7 else '朴实真挚' if score > 0.4 else '有待改进'}\n\n"
        
        breakdown += f"【具体分析】\n"
        breakdown += f"文本识别到{patriotic_count}个爱国相关词汇，"
        
        if score > 0.8:
            breakdown += "表现出了非常强烈的爱国情感，内容积极向上，具有很好的教育价值。"
        elif score > 0.6:
            breakdown += "体现了较强的爱国情感，表达真挚，有一定的感染力。"
        elif score > 0.4:
            breakdown += "具有基本的爱国意识，表达朴实，有进一步提升的空间。"
        else:
            breakdown += "爱国情感表达有待加强，建议通过多种方式提升表达质量。"
        
        return breakdown
    
    def _generate_standard_breakdown(self, text, score, patriotic_count, anti_patriotic_count):
        """生成标准分析报告"""
        text_length = len(text)
        intensity = "非常强烈" if score > 0.92 else "强烈" if score > 0.78 else "较强" if score > 0.55 else "一般" if score > 0.3 else "较弱"
        
        analysis = f"文本体现了{intensity}的爱国情感，识别到{patriotic_count}个爱国词汇和{anti_patriotic_count}个反爱国词汇，文本长度{text_length}字。"
        
        if score > 0.92:
            analysis += "文本内容优秀，爱国词汇丰富，表达深刻，充分体现了学生深厚的爱国情怀和强烈的民族自豪感。"
        elif score > 0.78:
            analysis += "文本内容良好，有一定的爱国词汇，体现了学生对祖国的热爱，但仍有提升空间。"
        elif score > 0.55:
            analysis += "文本内容一般，爱国情感表达基本合格，建议增加更多具体的爱国表达。"
        elif score > 0.3:
            analysis += "文本爱国情感表达较弱，建议加强爱国主义教育，提升表达的深度和广度。"
        else:
            analysis += "文本的爱国情感表达不足，需要大力加强爱国意识培养和表达能力训练。"
        
        return analysis


class BatchPatrioticAnalyzer:
    """批量爱国情感分析器"""
    
    def __init__(self):
        self.prompt_engineer = PatrioticPromptEngineer()
    
    def batch_analyze_homework(self, homework_id, prompt_type="standard", progress_callback=None):
        """批量分析作业的爱国情感（支持文本和代码作业）"""
        try:
            # 首先检查作业类型
            homework = Homework.query.get(homework_id)
            if not homework:
                return {'success': False, 'error': '作业不存在'}
            
            # 只处理文本作业
            if homework.homework_type != 'text':
                return {'success': False, 'error': '爱国情感分析只支持文本作业，请选择文本类型的作业'}
            
            upload_homeworks = Uploadhomework.query.filter_by(hnumber=homework_id).all()
            
            if not upload_homeworks:
                return {'success': False, 'error': '该作业暂无提交记录'}
            
            # 过滤只分析文本作业提交
            text_submissions = [uh for uh in upload_homeworks if uh.submission_type == 'text']
            
            if not text_submissions:
                return {'success': False, 'error': '该作业没有文本类型的提交记录'}
            
            results = []
            success_count = 0
            error_count = 0
            total_count = len(text_submissions)
            
            for i, upload_homework in enumerate(text_submissions):
                try:
                    if progress_callback:
                        progress_callback(i, total_count, f"正在分析 {upload_homework.student.name} 的作业...")
                    
                    # 获取文本作业内容
                    homework_content = self._get_homework_content(upload_homework)
                    if not homework_content:
                        error_count += 1
                        results.append({
                            'student_name': upload_homework.student.name,
                            'student_id': upload_homework.student.ID,
                            'class_id': upload_homework.student.class_id1,
                            'status': 'error',
                            'message': '无法获取作业内容'
                        })
                        continue
                    
                    patriotic_result = self.prompt_engineer.analyze_with_prompt(homework_content, prompt_type)
                    grade = self._calculate_patriotic_grade(patriotic_result['patriotic_score'])
                    
                    # 检查是否已存在分析结果
                    existing_analysis = PatrioticAnalysis.query.filter_by(upload_homework_id=upload_homework.ID).first()
                    if existing_analysis:
                        # 更新现有记录
                        existing_analysis.patriotic_score = patriotic_result['patriotic_score']
                        existing_analysis.patriotic_level = patriotic_result['patriotic_level']
                        existing_analysis.is_patriotic = patriotic_result['is_patriotic']
                        existing_analysis.patriotic_words_count = patriotic_result['patriotic_words_count']
                        existing_analysis.anti_patriotic_words_count = patriotic_result['anti_patriotic_words_count']
                        existing_analysis.confidence = patriotic_result['confidence']
                        existing_analysis.patriotic_breakdown = patriotic_result['patriotic_breakdown']
                        existing_analysis.grade = grade
                        existing_analysis.analysis_time = datetime.now()
                    else:
                        # 创建新记录
                        analysis = PatrioticAnalysis(
                            upload_homework_id=upload_homework.ID,
                            patriotic_score=patriotic_result['patriotic_score'],
                            patriotic_level=patriotic_result['patriotic_level'],
                            is_patriotic=patriotic_result['is_patriotic'],
                            patriotic_words_count=patriotic_result['patriotic_words_count'],
                            anti_patriotic_words_count=patriotic_result['anti_patriotic_words_count'],
                            confidence=patriotic_result['confidence'],
                            patriotic_breakdown=patriotic_result['patriotic_breakdown'],
                            grade=grade
                        )
                        db.session.add(analysis)
                    
                    upload_homework.grade = grade
                    success_count += 1
                    
                    results.append({
                        'student_name': upload_homework.student.name,
                        'student_id': upload_homework.student.ID,
                        'class_id': upload_homework.student.class_id1,
                        'status': 'success',
                        'patriotic_score': patriotic_result['patriotic_score'],
                        'patriotic_level': patriotic_result['patriotic_level'],
                        'grade': grade,
                        'confidence': patriotic_result['confidence'],
                        'patriotic_words_count': patriotic_result['patriotic_words_count'],
                        'anti_patriotic_words_count': patriotic_result['anti_patriotic_words_count'],
                        'model_type': patriotic_result['model_type'],
                        'prompt_type': patriotic_result.get('prompt_type', prompt_type),
                        'message': '分析完成'
                    })
                    
                except Exception as e:
                    error_count += 1
                    results.append({
                        'student_name': upload_homework.student.name,
                        'student_id': upload_homework.student.ID,
                        'class_id': upload_homework.student.class_id1,
                        'status': 'error',
                        'message': str(e)
                    })
            
            db.session.commit()
            
            return {
                'success': True,
                'total_count': total_count,
                'success_count': success_count,
                'error_count': error_count,
                'results': results,
                'prompt_type': prompt_type
            }
            
        except Exception as e:
            db.session.rollback()
            return {'success': False, 'error': f'批量分析失败: {str(e)}'}
    
    def _get_homework_content(self, upload_homework):
        """获取作业内容（支持文本作业和代码作业）"""
        try:
            # 如果是文本作业，直接从数据库获取
            if upload_homework.submission_type == 'text':
                return upload_homework.text_content
            
            # 如果是代码作业，从文件读取
            elif upload_homework.submission_type == 'code':
                return self._read_homework_content(upload_homework.homeworkpath)
            
            return None
            
        except Exception as e:
            print(f"获取作业内容失败: {str(e)}")
            return None
    
    def _read_homework_content(self, file_path):
        """读取作业文件内容"""
        if not file_path or not os.path.exists(file_path):
            return None
        
        try:
            file_ext = os.path.splitext(file_path)[1].lower()
            
            if file_ext in ['.txt', '.md']:
                with open(file_path, 'r', encoding='utf-8') as f:
                    return f.read()
            elif file_ext in ['.docx']:
                from docx import Document
                doc = Document(file_path)
                return '\n'.join([paragraph.text for paragraph in doc.paragraphs])
            elif file_ext in ['.pdf']:
                import PyPDF2
                with open(file_path, 'rb') as f:
                    pdf_reader = PyPDF2.PdfReader(f)
                    text = ''
                    for page in pdf_reader.pages:
                        text += page.extract_text()
                    return text
            else:
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        return f.read()
                except:
                    return None
                    
        except Exception as e:
            print(f"读取文件失败 {file_path}: {str(e)}")
            return None
    
    def _calculate_patriotic_grade(self, patriotic_score):
        """基于爱国情感得分计算评分"""
        base_score = int(patriotic_score * 100)
        
        if patriotic_score >= 0.8:
            bonus = 20
        elif patriotic_score >= 0.6:
            bonus = 15
        elif patriotic_score >= 0.4:
            bonus = 10
        elif patriotic_score >= 0.2:
            bonus = 5
        else:
            bonus = 0
        
        final_score = min(100, base_score + bonus)
        return final_score


# 初始化分析器
batch_analyzer = BatchPatrioticAnalyzer()


@bp.route('/')
def index():
    """爱国情感提示工程主页"""
    return render_template('patriotic_prompt/integrated_index.html')

@bp.route('/standalone')
def standalone_index():
    """独立版本主页"""
    return render_template('patriotic_prompt/index.html')


@bp.route('/batch_analyze', methods=['GET', 'POST'])
def batch_analyze():
    """批量分析页面"""
    if request.method == 'GET':
        # 只显示文本类型的作业
        homeworks = Homework.query.filter_by(homework_type='text').all()
        return render_template('patriotic_prompt/batch_analyze.html', homeworks=homeworks)
    
    homework_id = request.form.get('homework_id')
    prompt_type = request.form.get('prompt_type', 'standard')
    
    if not homework_id:
        return jsonify({'error': '请选择要分析的作业'}), 400
    
    try:
        result = batch_analyzer.batch_analyze_homework(homework_id, prompt_type)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': f'批量分析失败: {str(e)}'}), 500


@bp.route('/api/analyze_single', methods=['POST'])
def analyze_single():
    """单个文本分析API"""
    data = request.get_json()
    
    if not data or 'text' not in data:
        return jsonify({'error': '请提供文本内容'}), 400
    
    text = data['text']
    prompt_type = data.get('prompt_type', 'standard')
    
    try:
        result = batch_analyzer.prompt_engineer.analyze_with_prompt(text, prompt_type)
        return jsonify({'success': True, 'result': result})
    except Exception as e:
        return jsonify({'error': f'分析失败: {str(e)}'}), 500


@bp.route('/analysis_results/<int:homework_id>')
def analysis_results(homework_id):
    """查看分析结果"""
    analyses = PatrioticAnalysis.query.join(Uploadhomework).filter(
        Uploadhomework.hnumber == homework_id
    ).all()
    
    total_count = len(analyses)
    avg_score = sum(a.patriotic_score for a in analyses) / total_count if total_count > 0 else 0
    avg_grade = sum(a.grade for a in analyses if a.grade) / total_count if total_count > 0 else 0
    
    level_distribution = {}
    for analysis in analyses:
        level = analysis.patriotic_level
        level_distribution[level] = level_distribution.get(level, 0) + 1
    
    return render_template('patriotic_prompt/analysis_results.html',
                         analyses=analyses,
                         total_count=total_count,
                         avg_score=avg_score,
                         avg_grade=avg_grade,
                         level_distribution=level_distribution)


@bp.route('/detailed_analysis/<int:homework_id>')
def detailed_analysis(homework_id):
    """查看详细文字分析结果（无图表）"""
    analyses = PatrioticAnalysis.query.join(Uploadhomework).filter(
        Uploadhomework.hnumber == homework_id
    ).all()
    
    # 添加时间戳防止缓存
    import time
    current_timestamp = str(int(time.time()))
    
    if not analyses:
        return render_template('patriotic_prompt/detailed_analysis.html',
                             analyses=[], 
                             homework_id=homework_id,
                             message="暂无分析结果",
                             current_timestamp=current_timestamp)
    
    return render_template('patriotic_prompt/detailed_analysis.html',
                         analyses=analyses,
                         homework_id=homework_id,
                         current_timestamp=current_timestamp)


@bp.route('/update_grade', methods=['POST'])
def update_grade():
    """更新分析结果的评分"""
    try:
        data = request.json
        analysis_id = data.get('analysis_id')
        grade = data.get('grade')
        
        if not analysis_id or grade is None:
            return jsonify({'success': False, 'message': '缺少必要参数'})
        
        if not isinstance(grade, int) or grade < 0 or grade > 100:
            return jsonify({'success': False, 'message': '评分必须是0-100之间的整数'})
        
        # 查找分析记录
        analysis = PatrioticAnalysis.query.get(analysis_id)
        if not analysis:
            return jsonify({'success': False, 'message': '未找到分析记录'})
        
        # 更新评分
        analysis.grade = grade
        
        # 同时更新作业的评分
        if analysis.upload_homework:
            analysis.upload_homework.grade = grade
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': '评分更新成功'})
    
    except Exception as e:
        db.session.rollback()
        print(f"更新评分失败: {str(e)}")
        return jsonify({'success': False, 'message': f'更新失败: {str(e)}'})


@bp.route('/export_results/<int:homework_id>')
def export_results(homework_id):
    """导出分析结果到Excel"""
    analyses = PatrioticAnalysis.query.join(Uploadhomework).filter(
        Uploadhomework.hnumber == homework_id
    ).all()
    
    data = []
    for analysis in analyses:
        data.append({
            '学生姓名': analysis.upload_homework.student.name,
            '学号': analysis.upload_homework.student.ID,
            '班级': analysis.upload_homework.student.class_id1,
            '爱国情感得分': round(analysis.patriotic_score, 3),
            '爱国情感等级': analysis.patriotic_level,
            '是否具有爱国情感': '是' if analysis.is_patriotic else '否',
            '爱国词汇数量': analysis.patriotic_words_count,
            '反爱国词汇数量': analysis.anti_patriotic_words_count,
            '分析置信度': round(analysis.confidence, 3),
            '评分': analysis.grade,
            '分析时间': analysis.analysis_time.strftime('%Y-%m-%d %H:%M:%S') if analysis.analysis_time else '',
            '详细分析': analysis.patriotic_breakdown
        })
    
    df = pd.DataFrame(data)
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f'爱国情感分析结果_{homework_id}_{timestamp}.xlsx'
    filepath = os.path.join('static', filename)
    
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    
    with pd.ExcelWriter(filepath, engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name='分析结果', index=False)
        
        stats_data = {
            '统计项目': ['总分析数量', '平均爱国情感得分', '平均评分', '具有爱国情感数量', '不具有爱国情感数量'],
            '数值': [
                len(analyses),
                round(sum(a.patriotic_score for a in analyses) / len(analyses), 3) if analyses else 0,
                round(sum(a.grade for a in analyses if a.grade) / len(analyses), 1) if analyses else 0,
                sum(1 for a in analyses if a.is_patriotic),
                sum(1 for a in analyses if not a.is_patriotic)
            ]
        }
        stats_df = pd.DataFrame(stats_data)
        stats_df.to_excel(writer, sheet_name='统计信息', index=False)
    
    return jsonify({'success': True, 'download_url': url_for('static', filename=filename)})

